package com.jdkreader.concurent.forkjoin;


import java.util.concurrent.RecursiveTask;

/**
 * Fork/Join算法的简单实现
 *
 */
public class CountTaskDemo extends RecursiveTask {

    //任务尺度阈值，当需计算的值超过2时，使用Fork/Join算法
    public static final int THRESHOLD=2;

    public int startIndex;

    public int endIndex;

    public CountTaskDemo(int start, int end){
        this.startIndex=start;
        this.endIndex=end;
    }

    @Override
    protected Integer  compute() {

        int sum=0;

        boolean canCompute=(endIndex -startIndex) > THRESHOLD;


        if(!canCompute){
            for(int i = startIndex;i < endIndex; i++){
                sum+=i;
            }
        }else{

            int middle=(startIndex + endIndex)/2;

            CountTaskDemo leftTask=new CountTaskDemo(startIndex , middle);
            CountTaskDemo rightTask=new CountTaskDemo(middle + 1, endIndex);

            leftTask.fork();

            rightTask.fork();

            Integer leftResult=(Integer)leftTask.join();

            Integer rightResult=(Integer)rightTask.join();

            sum=leftResult+rightResult;
        }
        return sum;
    }

    public static void main(String[] args) {
        System.out.println(123);
    }

}
